package com.rico.deploy.controller;

import com.github.pagehelper.PageInfo;
import com.rico.common.response.MessageUtils;
import com.rico.common.response.RestResponse;
import com.rico.deploy.entity.College;
import com.rico.deploy.entity.Major;
import com.rico.deploy.service.CollegeService;
import com.rico.deploy.service.MajorService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @author 夏智力
 * @FileName MajorController
 * @date 2021/5/6 20:55
 * @Software: IntelliJ IDEA
 */
@Controller
@Slf4j
public class MajorController {

    @Autowired
    private MajorService majorService;

    @Autowired
    private CollegeService collegeService;


    @GetMapping("major/list")
    @ResponseBody
    public RestResponse getlist(Integer page, Integer limit) {
        log.info("{} {}", page, limit );
        List<Major> majors = majorService.selectAll(page, limit);
        PageInfo<Major> majorPageInfo = new PageInfo(majors);
        return MessageUtils.success(majorPageInfo.getList(), (int) majorPageInfo.getTotal());
    }

    @GetMapping("major/search")
    @ResponseBody
    public RestResponse search(String collegeName){
        List<Major> majors = majorService.selectMajorByCollegeName(collegeName);
        return MessageUtils.success(majors);
    }

    @GetMapping("major/delete")
    @ResponseBody
    public RestResponse deleteById(Integer id) {
        log.info("{}", id);
        String msg = null;
        if ( majorService.deleteMajorById(id) == 1 )
            msg = "删除成功";
        else
            msg = "删除失败";
        return MessageUtils.success(msg);
    }

    /**
     * 更新数据
     * @param major
     * @return
     */
    @PostMapping("major/put")
    @ResponseBody
    public RestResponse put(Major major) {
        major.setCollegeCode(collegeService.selectCollegeCodeByCollegeName(major.getCollegeName()));
        int i =majorService.updateMajor(major);
        if ( i == 0 )
            return MessageUtils.fail("编辑失败");

        else
            return MessageUtils.success("编辑成功");
    }

    /**
     * 添加数据
     * @param major
     * @return
     */
    @PostMapping("major/post")
    @ResponseBody
    public RestResponse post(Major major) {

        major.setCollegeCode(collegeService.selectCollegeCodeByCollegeName(major.getCollegeName()));
        int i = majorService.insertMajor(major);

        if ( i == 0 )
            return MessageUtils.fail("添加失败");

        else
            return MessageUtils.success("添加成功");
    }

    /**
     * 获取html页面
     * @return
     */
    @GetMapping("majorManage")
    public String gethtml(){
        return "page/majorManage";
    }
}
